<?php

$url = explode("/", $_SERVER['HTTP_REFERER']);
if (strcmp($url[count($url) - 1], 'register.php') != 0) {
  $is_indirect_link = true;
}

// Report all errors and ignor notices
error_reporting(E_ALL ^ E_NOTICE);

// Disable magic_quotes_runtime
set_magic_quotes_runtime(0);

// Set default timezone
date_default_timezone_set("Asia/Taipei");

$phpver = phpversion();
if ($phpver < '4.1.0') {
  $_GET = $HTTP_GET_VARS;
  $_POST = $HTTP_POST_VARS;
  $_SERVER = $HTTP_SERVER_VARS;
}
$phpver = explode(".", $phpver);
$phpver = "$phpver[0]$phpver[1]";
if ($phpver >= 41) {
  $PHP_SELF = $_SERVER['PHP_SELF'];
}

session_start();

//Set root path
$ROOT_DIR = realpath(dirname(__FILE__));
$ROOT_DIR = str_replace('\\', '/', $ROOT_DIR);

if (!$is_indirect_link) {
  $is_page_valid = true;
}
else {
  $is_page_valid = false;
}

// Validate form data
$error_msg = '';
if (strcmp(trim($_POST['username']), "") == 0)  {
  $error_msg = $error_msg . '請填寫姓名<br />';
  $is_page_valid = false;
}
else {
  if (mb_strlen(trim($_POST['username']), 'UTF-8')  == 1) {
    $error_msg = $error_msg . '姓名長度需超過 1<br />';
    $is_page_valid = false;
  }
}
if (strcmp(trim($_POST['affiliation']), "") == 0)  {
  $error_msg = $error_msg . '請填寫單位<br />';
  $is_page_valid = false;
}
else {
  if (mb_strlen(trim($_POST['affiliation']), 'UTF-8')  == 1) {
    $error_msg = $error_msg . '單位長度需超過 1<br />';
    $is_page_valid = false;
  }
}
if (strcmp(trim($_POST['title']), "") != 0)  {
  if (mb_strlen(trim($_POST['title']), 'UTF-8')  == 1) {
    $error_msg = $error_msg . '職稱長度需超過 1<br />';
    $is_page_valid = false;
  }
}
if (strcmp(trim($_POST['telephone']), "") != 0)  {
  $islocal = false;
  $ismobile = false;
  if (preg_match("/^0\d{1,2}-\d{6,8}/", trim($_POST['telephone']))) {
    $islocal = true;
  }
  if (preg_match("/^09\d{8}$/", trim($_POST['telephone']))) {
    $ismobile = true;
  }
  if (!$islocal && !$ismobile) {
    $error_msg = $error_msg . '電話號碼格式不正確<br />';
    $is_page_valid = false;
  }
}
if (strcmp(trim($_POST['email']), "") == 0)  {
  $error_msg = $error_msg . '請填寫電子郵件<br />';
  $is_page_valid = false;
}
else {
  if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", trim($_POST['email']))) {
    $error_msg = $error_msg . '電子郵件格式不正確<br />';
    $is_page_valid = false;
  }
}
if (strcmp(trim($_POST['division']), "") == 0)  {
  $error_msg = $error_msg . '請填寫參加組別<br />';
  $is_page_valid = false;
}
else {
  if (strcmp(trim($_POST['division']), 'other') == 0) {
    if (strcmp(trim($_POST['other_division']), '') == 0) {
      $error_msg = $error_msg . '請註明其他組別<br />';
      $is_page_valid = false;
    }
  }
}


if ($is_page_valid) {

  include("$ROOT_DIR/config.php");
  include("$ROOT_DIR/mysql_class.php");

  $db = new sql_db($db_host, $db_username, $db_password, $databse_name, false);
  if (!$db->db_connect_id) {
    echo mysql_error();
    session_unset();
    session_destroy();
    exit('無法連接資料庫！');
  }

  if (isset($_POST['username']) && isset($_POST['email'])) {
    $username = trim($_POST['username']);
    $email = trim($_POST['email']);
    $query = sprintf("SELECT * FROM registration WHERE username='%s' AND email='%s'", mysql_real_escape_string($username), mysql_real_escape_string($email));
    $sql_reg_check = $db->sql_query($query);
    $reg_check = $db->sql_numrows($sql_reg_check);

    if ($reg_check == 0) {
      $_SESSION['username'] = trim($_POST['username']);
      $_SESSION['affiliation'] = trim($_POST['affiliation']);
      $_SESSION['title'] = trim($_POST['title']);
      $_SESSION['telephone'] = trim($_POST['telephone']);
      $_SESSION['email'] = trim($_POST['email']);
      $_SESSION['division'] = $_POST['division'];
      $_SESSION['other_division'] = trim($_POST['other_division']);
      $lunch_time = $_POST['lunch_time'];
      if (is_null($lunch_time)) {
        $selected_lunch_time = '';
      }
      else {
        $selected_lunch_time = implode(",", $lunch_time);
      }
      $_SESSION['lunch_time'] = $selected_lunch_time;
      $_SESSION['is_vegetarian'] = $_POST['is_vegetarian'];
      $_SESSION['notes'] = trim($_POST['notes']);
      $_SESSION['needDisabledAccess'] = $_POST['needDisabledAccess'];
      $_SESSION['participateSubmission'] = $_POST['participateSubmission'];

      $query = sprintf("INSERT INTO `registration`(username, affiliation, title, telephone, email, division, other_division, lunch_time, is_vegetarian, notes, needDisabledAccess, participateSubmission, regdate, ipaddress)
                        VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', ('%s'), %d, '%s', %d, %d, NOW(), '%s');",
                        mysql_real_escape_string($_SESSION['username']),
                        mysql_real_escape_string($_SESSION['affiliation']),
                        mysql_real_escape_string($_SESSION['title']),
                        mysql_real_escape_string($_SESSION['telephone']),
                        mysql_real_escape_string($_SESSION['email']),
                        mysql_real_escape_string($_SESSION['division']),
                        mysql_real_escape_string($_SESSION['other_division']),
                        mysql_real_escape_string($_SESSION['lunch_time']),
                        intval($_SESSION['is_vegetarian']),
                        mysql_real_escape_string($_SESSION['notes']),
                        intval($_SESSION['needDisabledAccess']),
                        intval($_SESSION['participateSubmission']),
                        mysql_real_escape_string($_SERVER['REMOTE_ADDR'])
                      );
      $db->sql_query($query);
      $query = sprintf("SELECT * FROM registration WHERE username='%s' AND email='%s'", mysql_real_escape_string($_SESSION['username']), mysql_real_escape_string($_SESSION['email']));
      $sql_reg_check = $db->sql_query($query);
      $reg_check = $db->sql_numrows($sql_reg_check);

      if ($reg_check != 0) {
        include("$ROOT_DIR/class.phpmailer.php");

        $mail = new PHPMailer();

        $mail->IsSMTP();
        $mail->SMTPAuth   = true;                   // enable SMTP authentication
        $mail->SMTPSecure = "ssl";                  // sets the prefix to the servier
        $mail->Host       = "smtp.gmail.com";       // sets GMAIL as the SMTP server
        $mail->Port       = 465;                    // set the SMTP port for the GMAIL server
        $mail->Username   = "";                     // GMAIL username
        $mail->Password   = "";                     // GMAIL password
        $mail->CharSet    = "utf8";

        $mail->SetFrom("b93102063@ntu.edu.tw", "第四十八屆台灣心理學年會");
        $mail->AddReplyTo("b93102063@ntu.edu.tw", "第四十八屆台灣心理學年會");
        $mail->AddAddress($_SESSION['email'], $_SESSION['username']);
        $mail->Subject  = "第四十八屆台灣心理學年會報名確認信";

        $body = sprintf("%s 您好：\n\n感謝您的報名，若您有任何疑問，十分歡迎您來信詢問，電子郵件地址：b93102063@ntu.edu.tw。\n\nThank you very much for your on-line registration. If any question, you are very much welcome to contact us on b93102063@ntu.edu.tw.\n\n\n第四十八屆台灣心理學年會", $_SESSION['username']);
        $mail->Body = $body;

        if (!$mail->Send()) {
          $_SESSION['error_msg'] = $mail->ErrorInfo;
          header("Location: failure.php");
        } else {
          header("Location: success.php");
        }
      }
      else {
        $_SESSION['error_msg'] = '系統錯誤，報名失敗！';
        header("Location: failure.php");
      }
    }
    else {
      $row = $db->sql_fetchrow($sql_reg_check);
      $_SESSION['username'] = $row['username'];
      $_SESSION['email'] = $row['email'];
      $_SESSION['regdate'] = $row['regdate'];
      header("Location: duplicate.php");
    }
  }
  else {
    session_unset();
    session_destroy();
    exit("操作不允許！");
  }
}
else {
  if ($is_indirect_link) {
    header("Location: register.php");
  }
  else {
    if (strcmp(trim($_POST['username']), "") != 0) {
      $_SESSION['username'] = trim($_POST['username']);
    }
    else {
      $_SESSION['username'] = '';
    }
    if (strcmp(trim($_POST['affiliation']), "") != 0) {
      $_SESSION['affiliation'] = trim($_POST['affiliation']);
    }
    else {
      $_SESSION['affiliation'] = '';
    }
    if (strcmp(trim($_POST['title']), "") != 0) {
      $_SESSION['title'] = trim($_POST['title']);
    }
    else {
      $_SESSION['title'] = '';
    }
    if (strcmp(trim($_POST['telephone']), "") != 0) {
      $_SESSION['telephone'] = trim($_POST['telephone']);
    }
    else {
      $_SESSION['telephone'] = '';
    }
    if (strcmp(trim($_POST['email']), "") != 0) {
      $_SESSION['email'] = trim($_POST['email']);
    }
    else {
      $_SESSION['email'] = '';
    }
    if (!is_null($_POST['division'])) {
      $_SESSION['division'] = $_POST['division'];
    }
    if (strcmp(trim($_POST['other_division']), "") != 0) {
      $_SESSION['other_division'] = trim($_POST['other_division']);
    }
    else {
      $_SESSION['other_division'] = '';
    }
    if (!is_null($_POST['lunch_time'])) {
      $_SESSION['lunch_time'] = $_POST['lunch_time'];
    }
    else {
      $_SESSION['lunch_time'] = NULL;
    }
    if (strcmp(trim($_POST['is_vegetarian']), '') != 0) {
      $_SESSION['is_vegetarian'] = $_POST['is_vegetarian'];
    }
    if (strcmp(trim($_POST['notes']), "") != 0) {
      $_SESSION['notes'] = trim($_POST['notes']);
    }
    else {
      $_SESSION['notes'] = '';
    }
    if (strcmp(trim($_POST['needDisabledAccess']), "") != 0) {
      $_SESSION['needDisabledAccess'] = $_POST['needDisabledAccess'];
    }
    if (strcmp(trim($_POST['participateSubmission']), "") != 0) {
      $_SESSION['participateSubmission'] = $_POST['participateSubmission'];
    }

    $_SESSION['error_msg'] = $error_msg;

    header("Location: register.php");
  }
}

?>